<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="portlet" uri="http://java.sun.com/portlet_2_0"%>
<%@ taglib prefix="liferay-theme" uri="http://liferay.com/tld/theme"%>
<%@ taglib prefix="liferay-portlet" uri="http://liferay.com/tld/portlet"%>
<%@ page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@ page import="com.liferay.portal.util.PortalUtil"%>
<%@ page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
 
<portlet:defineObjects />
<liferay-theme:defineObjects/>

<%@ include file="permission.jsp" %>
<portlet:resourceURL id='exportTable' var='exportTable' />
<portlet:resourceURL var="resourceURL" escapeXml="false" id="resourceURLID"></portlet:resourceURL>

<%
String contextPath = request.getContextPath();
String serverKey="";
if (themeDisplay.getScopeGroup().getExpandoBridge().hasAttribute("server_key")) {
  serverKey = themeDisplay.getScopeGroup().getExpandoBridge().getAttribute("server_key").toString();
}
if (serverKey.isEmpty()) {
	serverKey = "http://127.0.0.1:8090/";
}
%>
<script type="text/javascript" src="<%=contextPath%>/js/moment.js"></script>
<script type="text/javascript">
    var context = {
    	hasViewCost:  <%=hasViewCost%>,
        path: '<%=contextPath%>/',
        ajaxURL : '${resourceURL}',
        base: '<%=contextPath%>/pages/assetproject/',
        jsPath: '${themeDisplay.getPathThemeJavaScript()}',
        action: {
        	countEquipmentByDay: '<%=contextPath%>/jsonActionProxy?serverKey=<%=serverKey%>&hostUrl=mis-server/rest/report/equipment/day',
        	countEquipmentByMonth: '<%=contextPath%>/jsonActionProxy?serverKey=<%=serverKey%>&hostUrl=mis-server/rest/report/equipment/month',
        	countEquipmentByYear: '<%=contextPath%>/jsonActionProxy?serverKey=<%=serverKey%>&hostUrl=mis-server/rest/report/equipment/year',
        },
        userId: <%=user.getUserId()%>,
        companyId: <%=user.getCompanyId()%>
    };
</script>

<style>
#tableHtml {
    overflow: auto;
}

#searchForm {
    background-color: #F2F2F2;
    padding-top: 5px;
}

#searchForm .layui-form-item {
    margin-bottom: 10px;
}

#reportTable tr th {
    background-color: #f2f2f2;
}

#reportTable tr:nth-of-type(odd) {
    background-color: #FFF;
}

#reportTable tr:nth-of-type(even) {
    background-color: #f2f2f2;
}

#reportTable .sum {
    font-weight: bold;
}
</style>

<form id="searchForm" class="layui-form layui-form-pane" action="${exportTable }">
    <div class="layui-row">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">统计方式</label>
                <div class="layui-input-inline">
                    <select name="modules" id="modules" lay-verify="required" lay-search="">
                        <option value="1">按天查询</option>
                        <option value="2">按月查询</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">开始时间</label>
                <div class="layui-input-inline">
                    <input type="text" name="fromDate" id="startTime" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">结束时间</label>
                <div class="layui-input-inline">
                    <input type="text" name="toDate" id="endTime" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">设备编码</label>
                <div class="layui-input-inline">
                    <input type="text" name="code" id="equipmentCode" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <button class="layui-btn layui-btn-sm" type="button" id="searchFormSearch"><i class="layui-icon layui-icon-search"></i>搜索</button>
                <button class="layui-btn layui-btn-sm" type="button" id="searchFormReset"><i class="layui-icon layui-icon-zzundo"></i>重置</button>
                <button class="layui-btn layui-btn-sm" type="button" id="exportExcel"><i class="layui-icon layui-icon-zzfile-excel-o"></i>导出EXCEL</button>
            </div>
        </div>
    </div>
</form>
<div id="tableHtml">
    <table class="layui-table" id="reportTable">
    </table>
</div>
<div class="layui-card">
    <div class="layui-card-header">设备任务机构</div>
    <div class="layui-card-body" style="height: 450px;" id="main"></div>
</div>

<script src="<%=request.getContextPath() %>/js/echarts.min.js"></script>
<script src="<%=request.getContextPath() %>/js/walden.js"></script>

<script>
function keepTwoDecimal(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
        alert('传递参数错误，请检查！');
        return false;
    }
    result = Math.round(num * 100) / 100;
    return result;
}

function genTableForDay(data) {

    var fromDate = $('#startTime').val(),
        toDate = $('#endTime').val();

    var diffMonths = function(StartDate, EndDate) {
        var StartDate = moment(StartDate),
            EndDate = moment(EndDate);
        let CurrentMonth = StartDate.startOf('month');
        let Months = [];
        while (CurrentMonth <= EndDate) {
            Months.push(CurrentMonth.clone());
            CurrentMonth = CurrentMonth.add(1, 'months');
        }
        return Months;
    }

    var monthDiff = diffMonths(fromDate, toDate);

    var start = moment(new Date(fromDate));
    var end = moment(new Date(toDate));

    var td = '';
    var table = "";

    // 月
    var monthRow = "<tr><th rowspan=2 nowrap=nowrap>设备编码</th><th rowspan=2 nowrap=nowrap>设备名称</th>";

    var s1 = moment(new Date(fromDate));
    for (var i = 1; i <= monthDiff.length; i++) {

        var e1 = moment(s1).endOf('month');

        var endDate = moment(toDate);
        if (e1.isAfter(moment(endDate))) {
            e1 = endDate;
        }
        var days = e1.diff(s1, 'days') + 1;
        if (monthDiff.length == 1 && start.isBefore(end)) {
            days++;
        }

        var month = s1.format('YYYY-MM');
        monthRow += '<th colspan=' + days + ' style="text-align:center">' + month + '</th>';

        s1 = moment(s1).startOf('month').add(1, 'month');
    }
    monthRow += '<th rowspan=2 class="sum">共计</th>';
    monthRow += (context.hasViewCost ? '<th rowspan=2 class="sum">成本</th>' : '');
    monthRow += '</tr>';
    
    
    start = moment(new Date(fromDate));
    end = moment(new Date(toDate));


    //日
    var dayRow = "<tr>";
    while (start.isBefore(end) || start.isSame(end)) {

        dayRow += '<td>' + start.format('DD') + '</td>';

        start.add(1, 'day');
    }
    dayRow += '</tr>';
    
    var thead = "<thead>" + monthRow + dayRow + "</thead>";

    // real data	  
    var line = '';
    var dateHourObj = {};
    var equipmentArr = ['总量'];
    var hourArr = [];
    var totalCost = 0;
    
    for (var i = 0; i < data.length; i++) {
        var row = data[i];

        equipmentArr.push(row.name);
        line += "<tr><td nowrap=nowrap>" + row.code + "</td><td nowrap=nowrap>" + row.name + "</td>";;

        start = moment(new Date(fromDate));
        end = moment(new Date(toDate));
        var totalHours = 0;

        while (start.isBefore(end) || start.isSame(end)) {
            var curDate = start.format('YYYY-MM-DD');
            var dates = row.workDateList;
            if (row.workDateList.indexOf(curDate) == -1) {
                line += '<td></td>';
            } else {                
                dates.forEach(function(item, index) {
                    if (item == curDate) {
                        //line += '<td title="有效工时:' + row.workHourList[index] + ' 制程异常工时:' + row.exceptionHourList[index] + ' 关联人数:' + row.employeeNumList[index] + '">' + row.totalHourList[index] + '</td>';
                        line += '<td>' + row.totalHourList[index] + '</td>';
                        totalHours += row.totalHourList[index];
                        typeof dateHourObj[curDate] == "undefined" ? (dateHourObj[curDate] = row.totalHourList[index]) : (dateHourObj[curDate] += row.totalHourList[index]);
                        return;
                    }
                });
            }

            start.add(1, 'day');
        }

        line += '<td class="sum">' + keepTwoDecimal(totalHours) + '</td>';
        hourArr.push(keepTwoDecimal(totalHours));
        
        if (context.hasViewCost) {
        	totalCost += row.workDateTotalCost;
        	line += '<td style="font-weight:bold">' + keepTwoDecimal(row.workDateTotalCost) + '</td>';
        }
        line += '</tr>';
        
    }


    // totalLine
    var totalLine = '<tr class="sum"><td colspan=2>合计(小时)</td>';
    start = moment(new Date(fromDate));
    end = moment(new Date(toDate));
    var total = 0;

    while (start.isBefore(end) || start.isSame(end)) {
        var curDate = start.format('YYYY-MM-DD');
        if (dateHourObj[curDate] != undefined) {
            total += dateHourObj[curDate];
            totalLine += '<td>' + keepTwoDecimal(dateHourObj[curDate]) + '</td>';
        } else {
            totalLine += '<td></td>';
        }
        start.add(1, 'day');
    }

    hourArr.splice(0, 0, keepTwoDecimal(total)); 
    totalLine += '<td>' + keepTwoDecimal(total) + '</td>';
    
    if (context.hasViewCost) {
    	totalLine += '<td style="font-weight:bold">' + keepTwoDecimal(totalCost) + '</td>';
    }
    totalLine += '</tr>';
    
    var tbody = "<tbody>" + line + totalLine + "</tbody>";

    var str = thead + tbody;
    $('#reportTable').html(str);


    showChart(equipmentArr, hourArr);
}

function genTableForMonth(data) {

    console.log('genTableForMonth');

    var fromDate = $('#startTime').val(),
        toDate = $('#endTime').val();

    var StartDate = moment(fromDate).startOf('month'),
        EndDate = moment(toDate).startOf('month');
    var monthNumber = 1;
    while (!StartDate.isSame(EndDate)) {
        ++monthNumber;
        StartDate.add(1, 'month');
    }

    var start = moment(new Date(fromDate));
    var end = moment(new Date(toDate));

    var td = '';
    var table = "";

    // 月
    var monthRow = "<tr><th rowspan=1 nowrap=nowrap>设备编码</th><th rowspan=1 nowrap=nowrap>设备名称</th>";

    var s1 = moment(new Date(fromDate));
    for (var i = 1; i <= monthNumber; i++) {

        var e1 = moment(s1).endOf('month');
        var endDate = moment(toDate);
        if (e1.isAfter(moment(endDate))) {
            e1 = endDate;
        }

        var month = s1.format('YYYY-MM');
        monthRow += '<th colspan=' + 1 + '>' + month + '</th>';

        s1 = moment(s1).startOf('month').add(1, 'month');
    }
    monthRow += '<th rowspan=1 class="sum">共计</th>';
    monthRow += (context.hasViewCost ? '<th rowspan=2 class="sum">成本</th>' : '');
    monthRow += '</tr>';
    
    var thead = "<thead>" + monthRow + "</thead>";

    start = moment(new Date(fromDate));
    end = moment(new Date(toDate));


    // data	  
    var line = '';
    var dateHourObj = {};
    var equipmentArr = ['总量'];
    var hourArr = [];
    var totalCost = 0;
    
    for (var i = 0; i < data.length; i++) {
        var row = data[i];

        equipmentArr.push(row.name);
        line += "<tr><td nowrap=nowrap>" + row.code + "</td><td nowrap=nowrap>" + row.name + "</td>";;

        start = moment(new Date(fromDate));
        end = moment(new Date(toDate));
        var totalHours = 0;

        for (var j = 1; j <= monthNumber; j++) {

            var curDate = start.startOf('month').format('YYYY-MM');
            var dates = row.workDateList;
            if (row.workDateList.indexOf(start.startOf('month').format('YYYY-MM-DD')) == -1) {
                line += '<td></td>';
            } else {               
                dates.forEach(function(item, index) {
                    if (moment(item).format('YYYY-MM') == curDate) {
                        //line += '<td title="有效工时:' + row.workHourList[index] + ' 制程异常工时:' + row.exceptionHourList[index] + ' 关联人数:' + row.employeeNumList[index] + '">' + row.totalHourList[index] + '</td>';
                        line += '<td>' + row.totalHourList[index] + '</td>';
                        totalHours += row.totalHourList[index];
                        typeof dateHourObj[curDate] == "undefined" ? (dateHourObj[curDate] = row.totalHourList[index]) : (dateHourObj[curDate] += row.totalHourList[index]);
                        return;
                    }
                });
            }

            start.add(1, 'month');
        }

        line += '<td class="sum">' + keepTwoDecimal(totalHours) + '</td>';
        hourArr.push(totalHours);
        

        if (context.hasViewCost) {
        	totalCost += row.workDateTotalCost;
        	line += '<td style="font-weight:bold">' + keepTwoDecimal(row.workDateTotalCost) + '</td>';
        }
        line += '</tr>';
    }


    var totalLine = '<tr class="sum"><td colspan=2>合计(小时)</td>';
    start = moment(new Date(fromDate));
    end = moment(new Date(toDate));
    var total = 0;
    start = moment(new Date(fromDate));
    end = moment(new Date(toDate));

    while (start.isBefore(end) || start.isSame(end)) {
        var curDate = start.format('YYYY-MM');
        if (dateHourObj[curDate] != undefined) {
            total += dateHourObj[curDate];
            totalLine += '<td>' + keepTwoDecimal(dateHourObj[curDate]) + '</td>';
        } else {
            totalLine += '<td></td>';
        }
        start.add(1, 'month');
    }

    hourArr.splice(0, 0, keepTwoDecimal(total)); 
    totalLine += '<td>' + keepTwoDecimal(total) + '</td>';    

    if (context.hasViewCost) {
    	totalLine += '<td style="font-weight:bold">' + keepTwoDecimal(totalCost) + '</td>';
    }
    totalLine += '</tr>';
    
    var tbody = "<tbody>" + line + totalLine + "</tbody>";
    
    var str = thead + tbody;
    $('#reportTable').html(str);

    showChart(equipmentArr, hourArr);
}

function showChart(equipmentArr, hourArr) {
		
    var myChart = echarts.init(document.getElementById('main'), 'walden');

    var option = {
        title: {
            text: '设备任务机构工时统计（单位:小时）',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            },
            /*
            formatter: function (params) {
                var tar = params[1];
                return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value;
            }
            */
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            splitLine: { show: false },
            //data : ['总量','电控配板', '机构装配', '气路安装', '对点调试', '手动调试', '自动调试', 'FAT','出货自检','设备出货'],
            data: equipmentArr
        },
        yAxis: {
            type: 'value'
        },
        series: [

            {
                name: '工时',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: true,
                        position: 'inside'
                    }
                },
                //data:[550, 120, 30, 20, 90,  120, 30, 20, 90,30]
                data: hourArr
            }
        ]
    };

    myChart.setOption(option);
}

layui.use(['form', 'layer', 'laydate'], function() {
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    //日期
    laydate.render({
        elem: '#startTime',
        showBottom: false
    });
    //日期
    laydate.render({
        elem: '#endTime',
        showBottom: false
    });
    //监听提交
    form.on('submit()', function(data) {
        $("#table").val($("#tableHtml").html());
        alert($("#table").val());
    });


    //设置高度自适应
    //var index = layer.getFrameIndex(window.name);
    //layer.iframeAuto(index);


    $('#startTime').val(moment(new Date()).startOf('month').format('YYYY-MM-DD'));
    $('#endTime').val(moment(new Date()).format('YYYY-MM-DD'));

    var searchForm = $("#searchForm");
    Lib.initSearchForm(searchForm,
        function() {
            if (!$('#startTime').val() || !$('#endTime').val()) {
                Lib.info('请选择时间');
                return;
            }

            var modules = $('#modules').val();
            
            var url = context.action.countEquipmentByDay;
            if (modules == "2") {
                url = context.action.countEquipmentByMonth;
            } else if (modules == "3") {
                url = context.action.countEquipmentByYear;
            }

            var param = 'fromDate=' + $('#startTime').val() + '&toDate=' + $('#endTime').val() 
        	+ '&modules=' + $('#modules').val() + '&code=' + encodeURIComponent(encodeURIComponent($('#equipmentCode').val()));
            
            $.ajax({
                url: url + '?' + param, //$("#searchForm").serialize(),
                type: "GET",
                success: function(rsp) {
                    if (rsp.success || rsp.code == 0) {
                        var modules = $('#modules').val();

                        if (modules == '1') {
                            genTableForDay(rsp.data);
                        } else if (modules == '2') {
                            genTableForMonth(rsp.data);
                        }

                    } else {
                        Lib.error(rsp.msg || '提交失败');
                    }
                },
                error: function(rsp) {
                    Lib.error(rsp.msg || '提交失败');
                }
            });
        }
    );
    
    $('#exportExcel').click(function() {
    	$('#reportTable').tableExport({ type: 'excel', escape: 'false', fileName: '设备工时统计', consoleLog: false });    	
    });

    $('#searchFormSearch').trigger('click');
});



(function ($) {
    $.fn.extend({
        tableExport: function (options) {
            var defaults = {
                consoleLog: false,
                csvEnclosure: '"',
                csvSeparator: ',',
                csvUseBOM: true,
                displayTableName: false,
                escape: false,
                excelstyles: ['border-bottom', 'border-top', 'border-left', 'border-right'],
                fileName: '导出数据',
                htmlContent: false,
                ignoreColumn: [],
                ignoreRow: [],
                jspdf: {
                    orientation: 'p',
                    unit: 'pt',
                    format: 'a4',
                    margins: { left: 20, right: 10, top: 10, bottom: 10 },
                    autotable: {
                        padding: 2,
                        lineHeight: 12,
                        fontSize: 8,
                        tableExport: {
                            onAfterAutotable: null,
                            onBeforeAutotable: null,
                            onTable: null
                        }
                    }
                },
                numbers: {
                    html: {
                        decimalMark: '.',
                        thousandsSeparator: ','
                    },
                    output: {
                        decimalMark: '.',
                        thousandsSeparator: ','
                    }
                },
                onCellData: null,
                outputMode: 'file', // file|string|base64
                tbodySelector: 'tr',
                theadSelector: 'tr',
                tableName: 'myTableName',
                type: 'csv',
                worksheetName: 'xlsWorksheetName'
            };


            var el = this;
            var DownloadEvt = null;
            var rowIndex = 0;
            var rowspans = [];
            var trData = '';


            $.extend(true, defaults, options);


            if (defaults.type == 'csv' || defaults.type == 'txt') {


                // Header
                var csvData = "";
                rowIndex = 0;
                $(el).find('thead').first().find(defaults.theadSelector).each(function () {
                    trData = "";
                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                trData += csvString(cell, row, col) + defaults.csvSeparator;
                            });
                    trData = $.trim(trData).substring(0, trData.length - 1);
                    if (trData.length > 0) {


                        if (csvData.length > 0)
                            csvData += "\n";


                        csvData += trData;
                    }
                    rowIndex++;
                });


                // Row vs Column
                $(el).find('tbody').first().find(defaults.tbodySelector).each(function () {
                    trData = "";
                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                trData += csvString(cell, row, col) + defaults.csvSeparator;
                            });
                    trData = $.trim(trData).substring(0, trData.length - 1);
                    if (trData.length > 0) {


                        if (csvData.length > 0)
                            csvData += "\n";


                        csvData += trData;
                    }
                    rowIndex++;
                });


                csvData += "\n";


                //output
                if (defaults.consoleLog === true)
                    console.log(csvData);


                if (defaults.outputMode === 'string')
                    return csvData;


                if (defaults.outputMode === 'base64')
                    return base64encode(csvData);


                try {
                    var blob = new Blob([((defaults.type == 'csv' && defaults.csvUseBOM) ? '\ufeff' : '') + csvData], { type: "text/" + (defaults.type == 'csv' ? 'csv' : 'plain') + ";charset=utf-8" });
                    saveAs(blob, defaults.fileName + '.' + defaults.type);
                }
                catch (e) {
                    downloadFile(defaults.fileName + '.' + defaults.type,
                            'data:text/' + (defaults.type == 'csv' ? 'csv' : 'plain') + ';charset=utf-8,' + ((defaults.type == 'csv' && defaults.csvUseBOM) ? '\ufeff' : '') +
                            encodeURIComponent(csvData));
                }


            } else if (defaults.type == 'sql') {


                // Header
                rowIndex = 0;
                var tdData = "INSERT INTO `" + defaults.tableName + "` (";
                $(el).find('thead').first().find(defaults.theadSelector).each(function () {


                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                tdData += "'" + parseString(cell, row, col) + "',";
                            });
                    rowIndex++;
                    tdData = $.trim(tdData);
                    tdData = $.trim(tdData).substring(0, tdData.length - 1);
                });
                tdData += ") VALUES ";
                // Row vs Column
                $(el).find('tbody').first().find(defaults.tbodySelector).each(function () {
                    trData = "";
                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                trData += "'" + parseString(cell, row, col) + "',";
                            });
                    if (trData.length > 3) {
                        tdData += "(" + trData;
                        tdData = $.trim(tdData).substring(0, tdData.length - 1);
                        tdData += "),";
                    }
                    rowIndex++;
                });


                tdData = $.trim(tdData).substring(0, tdData.length - 1);
                tdData += ";";


                //output
                if (defaults.consoleLog === true)
                    console.log(tdData);


                if (defaults.outputMode == 'string')
                    return tdData;


                if (defaults.outputMode == 'base64')
                    return base64encode(tdData);


                try {
                    var blob = new Blob([tdData], { type: "text/plain;charset=utf-8" });
                    saveAs(blob, defaults.fileName + '.sql');
                }
                catch (e) {
                    downloadFile(defaults.fileName + '.sql', 'data:application/sql;charset=utf-8,' + encodeURIComponent(tdData));
                }


            } else if (defaults.type == 'json') {


                var jsonHeaderArray = [];
                $(el).find('thead').first().find(defaults.theadSelector).each(function () {
                    var jsonArrayTd = [];


                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                jsonArrayTd.push(parseString(cell, row, col));
                            });
                    jsonHeaderArray.push(jsonArrayTd);
                });


                var jsonArray = [];
                $(el).find('tbody').first().find(defaults.tbodySelector).each(function () {
                    var jsonArrayTd = [];


                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                jsonArrayTd.push(parseString(cell, row, col));
                            });


                    if (jsonArrayTd.length > 0 && (jsonArrayTd.length != 1 || jsonArrayTd[0] != ""))
                        jsonArray.push(jsonArrayTd);


                    rowIndex++;
                });


                var jsonExportArray = [];
                jsonExportArray.push({ header: jsonHeaderArray, data: jsonArray });


                var sdata = JSON.stringify(jsonExportArray);


                if (defaults.consoleLog === true)
                    console.log(sdata);


                if (defaults.outputMode == 'string')
                    return sdata;


                var base64data = base64encode(sdata);


                if (defaults.outputMode == 'base64')
                    return base64data;


                try {
                    var blob = new Blob([sdata], { type: "application/json;charset=utf-8" });
                    saveAs(blob, defaults.fileName + '.json');
                }
                catch (e) {
                    downloadFile(defaults.fileName + '.json', 'data:application/json;charset=utf-8;base64,' + base64data);
                }


            } else if (defaults.type === 'xml') {


                rowIndex = 0;
                var xml = '<?xml version="1.0" encoding="utf-8"?>';
                xml += '<tabledata><fields>';


                // Header
                $(el).find('thead').first().find(defaults.theadSelector).each(function () {


                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                xml += "<field>" + parseString(cell, row, col) + "</field>";
                            });
                    rowIndex++;
                });
                xml += '</fields><data>';


                // Row Vs Column
                var rowCount = 1;
                $(el).find('tbody').first().find(defaults.tbodySelector).each(function () {
                    var colCount = 1;
                    trData = "";
                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                trData += "<column-" + colCount + ">" + parseString(cell, row, col) + "</column-" + colCount + ">";
                                colCount++;
                            });
                    if (trData.length > 0 && trData != "<column-1></column-1>") {
                        xml += '<row id="' + rowCount + '">' + trData + '</row>';
                        rowCount++;
                    }


                    rowIndex++;
                });
                xml += '</data></tabledata>';


                //output
                if (defaults.consoleLog === true)
                    console.log(xml);


                if (defaults.outputMode == 'string')
                    return xml;


                var base64data = base64encode(xml);


                if (defaults.outputMode == 'base64')
                    return base64data;


                try {
                    var blob = new Blob([xml], { type: "application/xml;charset=utf-8" });
                    saveAs(blob, defaults.fileName + '.xml');
                }
                catch (e) {
                    downloadFile(defaults.fileName + '.xml', 'data:application/xml;charset=utf-8;base64,' + base64data);
                }


            } else if (defaults.type == 'excel' || defaults.type == 'doc') {
                //console.log($(this).html());


                rowIndex = 0;
                var excelData = "<table>";
                // Header
                $(el).find('thead').first().find(defaults.theadSelector).each(function () {
                    trData = "";
                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                if (cell != null) {
                                    trData += "<td style='";
                                    for (var styles in defaults.excelstyles) {
                                        if (defaults.excelstyles.hasOwnProperty(styles)) {
                                            trData += defaults.excelstyles[styles] + ": " + $(cell).css(defaults.excelstyles[styles]) + ";";
                                        }
                                    }
                                    if ($(cell).is("[colspan]"))
                                        trData += "' colspan='" + $(cell).attr('colspan');
                                    if ($(cell).is("[rowspan]"))
                                        trData += "' rowspan='" + $(cell).attr('rowspan');
                                    trData += "'>" + parseString(cell, row, col) + "</td>";
                                }
                            });
                    if (trData.length > 0)
                        excelData += "<tr>" + trData + '</tr>';
                    rowIndex++;
                });


                // Row Vs Column
                $(el).find('tbody').first().find(defaults.tbodySelector).each(function () {
                    trData = "";
                    ForEachVisibleCell(this, 'th,td', rowIndex,
                            function (cell, row, col) {
                                if (cell != null) {
                                    trData += "<td style='";
                                    for (var styles in defaults.excelstyles) {
                                        if (defaults.excelstyles.hasOwnProperty(styles)) {
                                            trData += defaults.excelstyles[styles] + ": " + $(cell).css(defaults.excelstyles[styles]) + ";";
                                        }
                                    }
                                    if ($(cell).is("[colspan]"))
                                        trData += "' colspan='" + $(cell).attr('colspan');
                                    if ($(cell).is("[rowspan]"))
                                        trData += "' rowspan='" + $(cell).attr('rowspan');
                                    trData += "'>" + parseString(cell, row, col) + "</td>";
                                }
                            });
                    if (trData.length > 0)
                        excelData += "<tr>" + trData + '</tr>';
                    rowIndex++;
                });


                if (defaults.displayTableName)
                    excelData += "<tr><td></td></tr><tr><td></td></tr><tr><td>" + parseString($('<p>' + defaults.tableName + '</p>')) + "</td></tr>";


                excelData += '</table>';


                if (defaults.consoleLog === true)
                    console.log(excelData);


                var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:" + defaults.type + "' xmlns='http://www.w3.org/TR/REC-html40'>";
                excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-' + defaults.type + '; charset=UTF-8">';
                excelFile += '<meta http-equiv="content-type" content="application/';
                excelFile += (defaults.type === 'excel') ? 'vnd.ms-excel' : 'msword';
                excelFile += '; charset=UTF-8">';
                excelFile += "<head>";
                if (defaults.type === 'excel') {
                    excelFile += "<!--[if gte mso 9]>";
                    excelFile += "<xml>";
                    excelFile += "<x:ExcelWorkbook>";
                    excelFile += "<x:ExcelWorksheets>";
                    excelFile += "<x:ExcelWorksheet>";
                    excelFile += "<x:Name>";
                    excelFile += defaults.worksheetName;
                    excelFile += "</x:Name>";
                    excelFile += "<x:WorksheetOptions>";
                    excelFile += "<x:DisplayGridlines/>";
                    excelFile += "</x:WorksheetOptions>";
                    excelFile += "</x:ExcelWorksheet>";
                    excelFile += "</x:ExcelWorksheets>";
                    excelFile += "</x:ExcelWorkbook>";
                    excelFile += "</xml>";
                    excelFile += "<![endif]-->";
                }
                excelFile += "</head>";
                excelFile += "<body>";
                excelFile += excelData;
                excelFile += "</body>";
                excelFile += "</html>";


                if (defaults.outputMode == 'string')
                    return excelFile;


                var base64data = base64encode(excelFile);


                if (defaults.outputMode === 'base64')
                    return base64data;


                var extension = (defaults.type === 'excel') ? 'xls' : 'doc';
                try {
                    var blob = new Blob([excelFile], { type: 'application/vnd.ms-' + defaults.type });
                    saveAs(blob, defaults.fileName + '.' + extension);
                }
                catch (e) {
                    downloadFile(defaults.fileName + '.' + extension, 'data:application/vnd.ms-' + defaults.type + ';base64,' + base64data);
                }


            } else if (defaults.type == 'png') {
                html2canvas($(el), {
                    onrendered: function (canvas) {


                        var image = canvas.toDataURL();
                        image = image.substring(22); // remove data stuff


                        var byteString = atob(image);
                        var buffer = new ArrayBuffer(byteString.length);
                        var intArray = new Uint8Array(buffer);


                        for (var i = 0; i < byteString.length; i++)
                            intArray[i] = byteString.charCodeAt(i);


                        try {
                            var blob = new Blob([buffer], { type: "image/png" });
                            saveAs(blob, defaults.fileName + '.png');
                        }
                        catch (e) {
                            downloadFile(defaults.fileName + '.png', 'data:image/png;base64,' + image);
                        }
                    }
                });


            } else if (defaults.type == 'pdf') {
                if (defaults.jspdf.autotable === false) {
                    var addHtmlOptions = {
                        dim: {
                            w: getPropertyUnitValue($(el).first().get(0), 'width', 'mm'),
                            h: getPropertyUnitValue($(el).first().get(0), 'height', 'mm')
                        },
                        pagesplit: false
                    };


                    var doc = new jsPDF(defaults.jspdf.orientation, defaults.jspdf.unit, defaults.jspdf.format);
                    doc.addHTML($(el).first(),
                            defaults.jspdf.margins.left,
                            defaults.jspdf.margins.top,
                            addHtmlOptions,
                            function () {
                                jsPdfOutput(doc);
                            });
                    //delete doc;
                }
                else {
                    // pdf output using jsPDF AutoTable plugin
                    // https://github.com/someatoms/jsPDF-AutoTable


                    var teOptions = defaults.jspdf.autotable.tableExport;


                    // When setting jspdf.format to 'bestfit' tableExport tries to choose
                    // the minimum required paper format and orientation in which the table
                    // (or tables in multitable mode) completely fit without column adjustment
                    if (typeof defaults.jspdf.format === 'string' && defaults.jspdf.format.toLowerCase() === 'bestfit') {
                        var pageFormats = {
                            'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94],
                            'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55],
                            'a4': [595.28, 841.89]
                        };
                        var rk = '', ro = '';
                        var mw = 0;


                        $(el).filter(':visible').each(function () {
                            if ($(this).css('display') != 'none') {
                                var w = getPropertyUnitValue($(this).get(0), 'width', 'pt');


                                if (w > mw) {
                                    if (w > pageFormats['a0'][0]) {
                                        rk = 'a0';
                                        ro = 'l';
                                    }
                                    for (var key in pageFormats) {
                                        if (pageFormats.hasOwnProperty(key)) {
                                            if (pageFormats[key][1] > w) {
                                                rk = key;
                                                ro = 'l';
                                                if (pageFormats[key][0] > w)
                                                    ro = 'p';
                                            }
                                        }
                                    }
                                    mw = w;
                                }
                            }
                        });
                        defaults.jspdf.format = (rk == '' ? 'a4' : rk);
                        defaults.jspdf.orientation = (ro == '' ? 'w' : ro);
                    }


                    // The jsPDF doc object is stored in defaults.jspdf.autotable.tableExport,
                    // thus it can be accessed from any callback function from below
                    teOptions.doc = new jsPDF(defaults.jspdf.orientation,
                            defaults.jspdf.unit,
                            defaults.jspdf.format);


                    $(el).filter(':visible').each(function () {
                        if ($(this).css('display') != 'none') {
                            var colKey;
                            var rowIndex = 0;
                            var atOptions = {};


                            teOptions.columns = [];
                            teOptions.rows = [];
                            teOptions.rowoptions = {};


                            // onTable: optional callback function for every matching table that can be used
                            // to modify the tableExport options or to skip the output of a particular table
                            // when the  table selector targets multiple tables
                            if (typeof teOptions.onTable === 'function')
                                if (teOptions.onTable($(this), defaults) === false)
                                    return true; // continue to next iteration step (table)


                            // each table works with an own copy of AutoTable options
                            Object.keys(defaults.jspdf.autotable).forEach(function (key) {
                                atOptions[key] = defaults.jspdf.autotable[key];
                            });
                            atOptions.margins = {};
                            $.extend(true, atOptions.margins, defaults.jspdf.margins);


                            if (typeof atOptions.renderCell !== 'function') {


                                // draw cell text with original <td> alignment
                                atOptions.renderCell = function (x, y, width, height, key, value, row, settings) {
                                    var doc = settings.tableExport.doc;
                                    var xoffset = 0;


                                    doc.setFillColor(row % 2 === 0 ? 245 : 255);
                                    doc.setTextColor(50);
                                    doc.rect(x, y, width, height, 'F');
                                    y += settings.lineHeight / 2 + doc.autoTableTextHeight() / 2 - 2.5;


                                    if (typeof settings.tableExport.columns[key] != 'undefined') {
                                        var col = settings.tableExport.columns[key];
                                        if (typeof col.style != 'undefined') {
                                            var alignment = col.style.align;
                                            var rowopt = settings.tableExport.rowoptions[(row + 1) + ":" + key];


                                            if (typeof rowopt != 'undefined')
                                                alignment = rowopt.style.align;


                                            if (alignment == 'right')
                                                xoffset = width - doc.getStringUnitWidth(('' + value)) * doc.internal.getFontSize() - settings.padding;
                                            else if (alignment == 'center')
                                                xoffset = (width - doc.getStringUnitWidth(('' + value)) * doc.internal.getFontSize()) / 2;
                                        }
                                    }


                                    if (xoffset < settings.padding)
                                        xoffset = settings.padding;


                                    doc.text(value, x + xoffset, y);
                                }
                            }


                            // collect header and data rows
                            $(this).find('thead').find(defaults.theadSelector).each(function () {
                                colKey = 0;


                                ForEachVisibleCell(this, 'th,td', rowIndex,
                                        function (cell, row, col) {
                                            var obj = {
                                                title: parseString(cell, row, col),
                                                key: colKey++,
                                                style: {
                                                    align: getStyle(cell, 'text-align'),
                                                    bcolor: getStyle(cell, 'background-color')
                                                }
                                            };
                                            teOptions.columns.push(obj);
                                        });
                                rowIndex++;
                            });


                            $(this).find('tbody').find(defaults.tbodySelector).each(function () {
                                var rowData = [];
                                var rowCount = 0;
                                colKey = 0;


                                ForEachVisibleCell(this, 'th,td', rowIndex,
                                        function (cell, row, col) {
                                            var obj = {
                                                style: {
                                                    align: getStyle(cell, 'text-align'),
                                                    bcolor: getStyle(cell, 'background-color')
                                                }
                                            };
                                            teOptions.rowoptions[rowCount + ":" + colKey++] = obj;


                                            rowData.push(parseString(cell, row, col));
                                        });
                                if (rowData.length) {
                                    teOptions.rows.push(rowData);
                                    rowCount++
                                }
                                rowIndex++;
                            });


                            // onBeforeAutotable: optional callback function before calling
                            // jsPDF AutoTable that can be used to modify the AutoTable options
                            if (typeof teOptions.onBeforeAutotable === 'function')
                                teOptions.onBeforeAutotable($(this), teOptions.columns, teOptions.rows, atOptions);


                            teOptions.doc.autoTable(teOptions.columns, teOptions.rows, atOptions);


                            // onAfterAutotable: optional callback function after returning
                            // from jsPDF AutoTable that can be used to modify the AutoTable options
                            if (typeof teOptions.onAfterAutotable === 'function')
                                teOptions.onAfterAutotable($(this), atOptions);


                            // set the start position for the next table (in case there is one)
                            defaults.jspdf.autotable.startY = teOptions.doc.autoTableEndPosY() + atOptions.margins.top;
                        }
                    });


                    jsPdfOutput(teOptions.doc);


                    teOptions.columns.length = 0;
                    teOptions.rows.length = 0;
                    delete teOptions.doc;
                    teOptions.doc = null;
                }
            }


            function ForEachVisibleCell(tableRow, selector, rowIndex, cellcallback) {
                if (defaults.ignoreRow.indexOf(rowIndex) == -1) {
                    $(tableRow).filter(':visible').find(selector).each(function (colIndex) {
                        if ($(this).data("tableexport-display") == 'always' ||
                            ($(this).css('display') != 'none' &&
                             $(this).css('visibility') != 'hidden' &&
                             $(this).data("tableexport-display") != 'none')) {
                            if (defaults.ignoreColumn.indexOf(colIndex) == -1) {
                                if (typeof (cellcallback) === "function") {
                                    var cs = 0; // colspan value


                                    // handle previously detected rowspans
                                    if (typeof rowspans[rowIndex] != 'undefined' && rowspans[rowIndex].length > 0) {
                                        for (c = 0; c <= colIndex; c++) {
                                            if (typeof rowspans[rowIndex][c] != 'undefined') {
                                                cellcallback(null, rowIndex, c);
                                                delete rowspans[rowIndex][c];
                                                colIndex++;
                                            }
                                        }
                                    }


                                    // output content of current cell
                                    cellcallback(this, rowIndex, colIndex);


                                    // handle colspan of current cell
                                    if ($(this).is("[colspan]")) {
                                        cs = $(this).attr('colspan');
                                        for (c = 0; c < cs - 1; c++)
                                            cellcallback(null, rowIndex, colIndex + c);
                                    }


                                    // store rowspan for following rows
                                    if ($(this).is("[rowspan]")) {
                                        var rs = parseInt($(this).attr('rowspan'));


                                        for (r = 1; r < rs; r++) {
                                            if (typeof rowspans[rowIndex + r] == 'undefined')
                                                rowspans[rowIndex + r] = [];
                                            rowspans[rowIndex + r][colIndex] = "";


                                            for (c = 1; c < cs; c++)
                                                rowspans[rowIndex + r][colIndex + c] = "";
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }


            function jsPdfOutput(doc) {
                if (defaults.consoleLog === true)
                    console.log(doc.output());


                if (defaults.outputMode == 'string')
                    return doc.output();


                if (defaults.outputMode == 'base64')
                    return base64encode(doc.output());


                try {
                    var blob = doc.output('blob');
                    saveAs(blob, defaults.fileName + '.pdf');
                }
                catch (e) {
                    downloadFile(defaults.fileName + '.pdf', 'data:application/pdf;base64,' + base64encode(doc.output()));
                }
            }


            function escapeRegExp(string) {
                return string.replace(/([.*+?^=!:$\{\}\(\)\|\/\\])/g, "\\$1");
            }


            function replaceAll(string, find, replace) {
                return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
            }


            function csvString(cell, rowIndex, colIndex) {
                var result = '';


                if (cell != null) {
                    var dataString = parseString(cell, rowIndex, colIndex);


                    var csvValue = (dataString === null || dataString == '') ? '' : dataString.toString();


                    if (dataString instanceof Date)
                        result = defaults.csvEnclosure + dataString.toLocaleString() + defaults.csvEnclosure;
                    else {
                        result = replaceAll(csvValue, defaults.csvEnclosure, defaults.csvEnclosure + defaults.csvEnclosure);


                        if (result.indexOf(defaults.csvSeparator) >= 0 || /[\r\n ]/g.test(result))
                            result = defaults.csvEnclosure + result + defaults.csvEnclosure;
                    }
                }


                return result;
            }


            function parseNumber(value) {
                value = value || "0";
                value = replaceAll(value, defaults.numbers.html.decimalMark, '.');
                value = replaceAll(value, defaults.numbers.html.thousandsSeparator, '');


                return typeof value === "number" || jQuery.isNumeric(value) !== false ? value : false;
            }




            function parseString(cell, rowIndex, colIndex) {
                var result = '';


                if (cell != null) {
                    var $cell = $(cell);


                    if (defaults.htmlContent === true) {
                        result = $cell.html().trim();
                    }
                    else {
                        result = $cell.text().trim().replace(/\u00AD/g, ""); // remove soft hyphens


                        if (defaults.numbers.html.decimalMark != defaults.numbers.output.decimalMark ||
                            defaults.numbers.html.thousandsSeparator != defaults.numbers.output.thousandsSeparator) {
                            var number = parseNumber(result);


                            if (number !== false) {
                                var frac = ("" + number).split('.');
                                if (frac.length == 1)
                                    frac[1] = "";
                                var mod = frac[0].length > 3 ? frac[0].length % 3 : 0;


                                result = (number < 0 ? "-" : "") +
                                         (defaults.numbers.output.thousandsSeparator ? ((mod ? frac[0].substr(0, mod) + defaults.numbers.output.thousandsSeparator : "") + frac[0].substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + defaults.numbers.output.thousandsSeparator)) : frac[0]) +
                                         (frac[1].length ? defaults.numbers.output.decimalMark + frac[1] : "");
                            }
                        }
                    }


                    if (defaults.escape === true) {
                        result = escape(result);
                    }


                    if (typeof defaults.onCellData === 'function') {
                        result = defaults.onCellData($cell, rowIndex, colIndex, result);
                    }
                }


                return result;
            }


            function hyphenate(a, b, c) {
                return b + "-" + c.toLowerCase();
            }


            // get computed style property
            function getStyle(target, prop) {
                try {
                    if (window.getComputedStyle) { // gecko and webkit
                        prop = prop.replace(/([a-z])([A-Z])/, hyphenate);  // requires hyphenated, not camel
                        return window.getComputedStyle(target, null).getPropertyValue(prop);
                    }
                    if (target.currentStyle) { // ie
                        return target.currentStyle[prop];
                    }
                    return target.style[prop];
                }
                catch (e) {
                }
                return "";
            }


            function getPropertyUnitValue(target, prop, unit) {
                var baseline = 100;  // any number serves


                var value = getStyle(target, prop);  // get the computed style value


                var numeric = value.match(/\d+/);  // get the numeric component
                if (numeric !== null) {
                    numeric = numeric[0];  // get the string


                    var temp = document.createElement("div");  // create temporary element
                    temp.style.overflow = "hidden";  // in case baseline is set too low
                    temp.style.visibility = "hidden";  // no need to show it


                    target.parentElement.appendChild(temp); // insert it into the parent for em, ex and %


                    temp.style.width = baseline + unit;
                    var factor = baseline / temp.offsetWidth;


                    target.parentElement.removeChild(temp);  // clean up


                    return (numeric * factor);
                }
                return 0;
            }


            function downloadFile(filename, data) {
                var DownloadLink = document.createElement('a');


                if (DownloadLink) {
                    document.body.appendChild(DownloadLink);
                    DownloadLink.style = 'display: none';
                    DownloadLink.download = filename;
                    DownloadLink.href = data;


                    if (document.createEvent) {
                        if (DownloadEvt == null)
                            DownloadEvt = document.createEvent('MouseEvents');


                        DownloadEvt.initEvent('click', true, false);
                        DownloadLink.dispatchEvent(DownloadEvt);
                    }
                    else if (document.createEventObject)
                        DownloadLink.fireEvent('onclick');
                    else if (typeof DownloadLink.onclick == 'function')
                        DownloadLink.onclick();


                    document.body.removeChild(DownloadLink);
                }
            }


            function utf8Encode(string) {
                string = string.replace(/\x0d\x0a/g, "\x0a");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    }
                    else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                    else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                }
                return utftext;
            }


            function base64encode(input) {
                var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
                var output = "";
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;
                input = utf8Encode(input);
                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);
                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;
                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }
                    output = output +
                            keyStr.charAt(enc1) + keyStr.charAt(enc2) +
                            keyStr.charAt(enc3) + keyStr.charAt(enc4);
                }
                return output;
            }


            return this;
        }
    });
})(jQuery);
</script>
<a id="dlink" style="display:none"></a>
